package com.common.convert;

import com.common.convert.impl.OfficeConverter;
import com.common.convert.param.FormatParam;
import lombok.Data;
import org.jodconverter.core.document.DefaultDocumentFormatRegistry;
import org.jodconverter.core.document.DocumentFormat;

import java.io.File;
import java.util.*;

/**
 * @author lxw
 */
@Data
public class ConverterRouter implements Converter<Object> {


    private String outDir;

    private Map<FormatSupport, List<Converter>> converterMap = new LinkedHashMap<>();

    Set<FormatSupport> formatSupports = new HashSet<>();
    {
        register(new OfficeConverter());
    }

    public String convert( Object inputFile, String outType , List<FormatParam> params) {
        DocumentFormat fromSource = getFormat((File)inputFile);
        DocumentFormat toSource = DefaultDocumentFormatRegistry.getFormatByExtension(outType);
        FormatSupport formatSupport = new FormatSupport(fromSource, toSource);
        if (converterMap.containsKey(formatSupport)) {
            List<Converter> converters = converterMap.get(formatSupport);
            Exception exception = null;
            for (Converter converter : converters) {
                try {
                    return converter.convert(inputFile, outType);
                } catch (Exception e) {
                    exception = e;
                    e.printStackTrace();
                }
            }
            throw new ConvertException(exception);
        }
        throw new ConvertException("不支持从：" + getType(((File)inputFile).getName()) + "转成：" + outType);
    }

    private void register(Converter converter) {
        formatSupports.addAll(converter.supports());
        converter.supports().forEach(formatSupport -> {
            List<Converter> converters = converterMap.get(formatSupport);
            if (converters == null) {
                converterMap.put((FormatSupport)formatSupport, Collections.singletonList(converter));
            } else {
                converters.add(converter);
            }
        });
    }

    @Override
    public Set<FormatSupport> supports() {
        return formatSupports;
    }


}
